//
//  WYJRefreshControl.swift
//  MySinaWeibo
//
//  Created by eastriver on 17/3/9.
//  Copyright © 2017年 believewilliam. All rights reserved.
//

import UIKit
// 定义一个下拉刷新的枚举类型
enum WYJRefreshState : Int {
    case NORMAL
    case BEGIN
    case REFRESHING
}
// 定义一个刷新控件的高度全局常量
private let refreshHeight: CGFloat = 50

class WYJRefreshControl: UIControl {
    // 懒加载属性
    private lazy var backgroundImgV = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))// 此图片#imageLiteral(resourceName: "refreshbg")应该是经过特殊处理了，背景是透明的，所以程序启动后，如果WYJRefreshControl有背景色，透过#imageLiteral(resourceName: "refreshbg")能够看到背景色。正常应该看不到。
    private lazy var arrowImgV = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    private lazy var tipLabel = UILabel(title: "下拉刷新", textColor: UIColor.orange, fontSize: 14)
    private lazy var indicatorView = UIActivityIndicatorView()
    private var fatherScrollView: UIScrollView?
    // 定义一个下拉刷新的状态属性
    var refreshState: WYJRefreshState = .NORMAL {
        didSet {
            switch refreshState {
            case .NORMAL:
                self.tipLabel.text = "下拉刷新"
                // 箭头回归原位
                UIView.animate(withDuration: 0.25, animations: {
                    self.arrowImgV.transform = CGAffineTransform.identity
                })
                // 如果是请求数据后赋值NORMAL，则自定义刷新控件的位置也回归原位；并且，活动指示器停止转动。
                if oldValue == .REFRESHING {
                     self.indicatorView.stopAnimating()
                    // 以动画的形式回归原位
                    UIView.animate(withDuration: 0.5, animations: { 
                        self.fatherScrollView?.contentInset.top -= refreshHeight
//                     self.scrollView?.contentOffset.y = -64
                    })
                }
            case .BEGIN:
                self.tipLabel.text = "开始刷新"
                // 箭头旋转
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowImgV.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
            default:
                self.tipLabel.text = "正在刷新中"
                // 发出刷新事件
                self.sendActions(for: .valueChanged)
                self.arrowImgV.isHidden = true
                self.indicatorView.startAnimating()
                self.fatherScrollView?.contentInset.top += refreshHeight
//                self.scrollView?.contentOffset.y = -114
            }
        }
    }
    
    override init(frame: CGRect) {
        let refreshFrame = CGRect(x: 0, y: -refreshHeight, width: screenWidth, height: refreshHeight)
        super.init(frame: refreshFrame)
//        self.backgroundColor = randomColor()
        setupUI()
    }
    
    func setupUI() {
        addSubview(backgroundImgV)
        addSubview(arrowImgV)
        addSubview(tipLabel)
        addSubview(indicatorView)
        backgroundImgV.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
        tipLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(10)
        }
        arrowImgV.snp.makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.right.equalTo(tipLabel.snp.left).offset(-5)
        }
        indicatorView.snp.makeConstraints { (make) in
            make.center.equalTo(arrowImgV)
        }
        
        
    }
    // 自定义停止刷新的方法
    func endRefreshing() {
        // 延迟0.5秒后再执行
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.refreshState = .NORMAL
        }
    }
    override func willMove(toSuperview newSuperview: UIView?) {
        // 在此获取homeTableView
        if let fatherView = (newSuperview as? UIScrollView) {
            self.fatherScrollView = fatherView
        }
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        /*
         // 此处不知道如何用change参数来获取contentOffset
        print(change![NSKeyValueChangeKey.newKey])
         */
        let offsetY = self.fatherScrollView!.contentOffset.y
        let targetY = -(64 + refreshHeight)
        if (self.fatherScrollView?.isDragging)! {
            if self.refreshState == .NORMAL && offsetY < targetY {
                self.refreshState = .BEGIN
                
            }else if self.refreshState == .BEGIN && offsetY > targetY {
                self.refreshState = .NORMAL
                
            }
        } else {
            if self.refreshState == .BEGIN {
                self.refreshState = .REFRESHING
                
            }
        }
        
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        self.fatherScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
